package com.atguigu.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/7/28 9:07
 */
public class DimUtil {
    public static JSONObject readDimFromPhoenix(Connection phoenixConn, String table,
                                                String id) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
        
        String sql = "select * from " + table + " where id=?";
        Object[] args = {id};
        // 使用标准的jdbc去查询表
        // select * from a where id=? and name=?
        // 查询的结果是多行多列
        List<JSONObject> list = JdbcUtil.queryList(phoenixConn, sql, args, JSONObject.class);
        // 咱们是根据id查询的维度信息, 那么list中一定只有一行
        if (list.size() == 0) {
            throw new RuntimeException("你要查询的维度信息不存在: " + table + "  " + id);
        }
        return list.get(0);
    }
    
    public static JSONObject readDim(Jedis redisClient,
                                     Connection phoenixConn,
                                     String table,
                                     String id) throws InvocationTargetException, SQLException, InstantiationException, IllegalAccessException {
        // 读取维度: 先从redis读, 如果没有, 再从Phoenix读
        JSONObject dim = readDimFromRedis(redisClient, table, id);
        // 如果dim是null, 表示缓存中没有, 从Phoenix读
        if (dim == null) {
            System.out.println("走数据库: " + table + "  " + id);
            dim = readDimFromPhoenix(phoenixConn, table, id);
            // dim从Phoenix读到了. 然后应该把dim缓存到redis
            writeDimToRedis(redisClient, table, id, dim);
        } else {
            System.out.println("走缓存: " + table + "  " + id);
        }
        
        return dim;
    }
    
    //TODO
    private static void writeDimToRedis(Jedis redisClient, String table, String id, JSONObject dim) {
        // 写到string key  value
        
        String key = table + ":" + id;
        String value = dim.toJSONString();
        
       /* redisClient.set(key, value);
        redisClient.expire(key, 2 * 24 * 60 * 60);  // 2天的过期时间*/
        
        redisClient.setex(key, 2 * 24 * 60 * 60, value);
    }
    
    //TODO
    private static JSONObject readDimFromRedis(Jedis redisClient, String table, String id) {
        String key = table + ":" + id;
        
        String json = redisClient.get(key);
        
        JSONObject dim = null;
        if (json != null) {
            dim = JSON.parseObject(json);
        }
        return dim;
    }
}
